package com.utcook.host.fragmentdialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.Observable
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.FragmentRecipeBinding

class RecipeFragment : Fragment() {

    private var _binding: FragmentRecipeBinding? = null
    private val binding get() = _binding!!
    private val burnerViewModel = BurnerViewModel()

    private val burnerFragments = mutableListOf<BurnerFragment>()
    private var recipeOperationFragment: RecipeOperationFragment? = null
    private var recipeCookingFragment: RecipeCookingFragment? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecipeBinding.inflate(inflater, container, false)
        binding.fragment = this
        binding.viewModel = burnerViewModel
        
        setupBurnerFragments()
        setupRecipeOperationFragment()
        setupCookingStateListener()
        
        return binding.root
    }

    private fun setupBurnerFragments() {
        // 创建4个炉头Fragment
        for (i in 0..3) {
            val burnerFragment = BurnerFragment.newInstance(i, burnerViewModel)
            burnerFragments.add(burnerFragment)
            
            // 添加到对应的容器
            val containerId = when (i) {
                0 -> binding.burner1Container.id
                1 -> binding.burner2Container.id
                2 -> binding.burner3Container.id
                3 -> binding.burner4Container.id
                else -> binding.burner1Container.id
            }
            
            childFragmentManager.beginTransaction()
                .replace(containerId, burnerFragment)
                .commit()
        }
        
        // 设置ViewModel状态变化监听
        setupViewModelListener()
    }
    
    private fun setupRecipeOperationFragment() {
        recipeOperationFragment = RecipeOperationFragment.newInstance(burnerViewModel)
        childFragmentManager.beginTransaction()
            .replace(R.id.recipe_operation_container, recipeOperationFragment!!, "recipe_operation")
            .commit()
    }
    
    private fun setupViewModelListener() {
        burnerViewModel.selectedBurnerIndex.addOnPropertyChangedCallback(
            object : Observable.OnPropertyChangedCallback() {
                override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                    updateAllBurnerFragments()
                    // 当炉头切换时，清空选中的菜谱，这样再次点击同一菜谱时会触发选择事件
                    burnerViewModel.selectedRecipe.set(null)
                    // 当炉头切换时，更新右侧内容
                    updateRightContent()
                }
            }
        )
    }
    
    private fun setupCookingStateListener() {
        // 监听选中的菜谱变化
        burnerViewModel.selectedRecipe.addOnPropertyChangedCallback(
            object : androidx.databinding.Observable.OnPropertyChangedCallback() {
                override fun onPropertyChanged(sender: androidx.databinding.Observable?, propertyId: Int) {
                    burnerViewModel.selectedRecipe.get()?.let { recipe ->
                        val selectedBurnerIndex = burnerViewModel.selectedBurnerIndex.get()
                        android.util.Log.d("RecipeFragment", "菜谱被选中: ${recipe.name}, 炉头: $selectedBurnerIndex")
                        burnerViewModel.startCookingOnBurner(selectedBurnerIndex, recipe)
                        // 直接触发页面切换
                        showRecipeCooking(recipe, selectedBurnerIndex)
                    }
                }
            }
        )
        
        // 监听烹饪状态变化
        burnerViewModel.burnerCookingStates.addOnListChangedCallback(
            object : androidx.databinding.ObservableList.OnListChangedCallback<androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>>() {
                override fun onChanged(sender: androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>?) {
                    updateRightContent()
                }
                
                override fun onItemRangeChanged(sender: androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>?, positionStart: Int, itemCount: Int) {
                    updateRightContent()
                }
                
                override fun onItemRangeInserted(sender: androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>?, positionStart: Int, itemCount: Int) {
                    updateRightContent()
                }
                
                override fun onItemRangeMoved(sender: androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>?, fromPosition: Int, toPosition: Int, itemCount: Int) {
                    updateRightContent()
                }
                
                override fun onItemRangeRemoved(sender: androidx.databinding.ObservableList<BurnerViewModel.BurnerCookingState>?, positionStart: Int, itemCount: Int) {
                    updateRightContent()
                }
            }
        )
    }
    
    private fun updateRightContent() {
        val selectedBurnerIndex = burnerViewModel.selectedBurnerIndex.get()
        val cookingState = burnerViewModel.getBurnerCookingState(selectedBurnerIndex)
        
        android.util.Log.d("RecipeFragment", "updateRightContent: 炉头$selectedBurnerIndex, 烹饪状态: ${cookingState?.isCooking}, 完成状态: ${cookingState?.isCompleted}")
        
        if (cookingState?.isCooking == true || cookingState?.isCompleted == true) {
            // 显示烹饪页面（包括烹饪中和烹饪完成但未返回的情况）
            android.util.Log.d("RecipeFragment", "显示烹饪页面")
            showRecipeCooking(cookingState.currentRecipe!!, selectedBurnerIndex)
        } else {
            // 显示菜谱操作页面
            android.util.Log.d("RecipeFragment", "显示菜谱操作页面")
            showRecipeOperation()
        }
    }
    
    private fun updateCookingDisplay() {
        val selectedBurnerIndex = burnerViewModel.selectedBurnerIndex.get()
        val cookingState = burnerViewModel.getBurnerCookingState(selectedBurnerIndex)
        
        android.util.Log.d("RecipeFragment", "updateCookingDisplay: 炉头$selectedBurnerIndex, 烹饪状态: ${cookingState?.isCooking}")
        
        if (cookingState?.isCooking == true) {
            // 显示烹饪页面
            android.util.Log.d("RecipeFragment", "显示烹饪页面")
            showRecipeCooking(cookingState.currentRecipe!!, selectedBurnerIndex)
        } else {
            // 显示菜谱操作页面
            android.util.Log.d("RecipeFragment", "显示菜谱操作页面")
            showRecipeOperation()
        }
    }
    
    private fun showRecipeCooking(recipe: Recipe, burnerIndex: Int) {
        android.util.Log.d("RecipeFragment", "showRecipeCooking: 菜谱${recipe.name}, 炉头$burnerIndex")
        val transaction = childFragmentManager.beginTransaction()
        
        // 隐藏菜谱操作页面
        val operationFragment = childFragmentManager.findFragmentByTag("recipe_operation")
        operationFragment?.let { transaction.hide(it) }
        
        // 隐藏其他炉头的烹饪页面
        for (i in 0..3) {
            if (i != burnerIndex) {
                val cookingFragment = childFragmentManager.findFragmentByTag("recipe_cooking_$i")
                cookingFragment?.let { transaction.hide(it) }
            }
        }
        
        // 检查是否已存在该炉头的烹饪页面
        val existingFragment = childFragmentManager.findFragmentByTag("recipe_cooking_$burnerIndex")
        if (existingFragment != null) {
            // 如果已存在，直接显示（不重置状态）
            android.util.Log.d("RecipeFragment", "显示已存在的炉头${burnerIndex + 1}烹饪Fragment")
            transaction.show(existingFragment)
            transaction.commit()
            // 在事务提交后，让Fragment更新状态
            (existingFragment as? RecipeCookingFragment)?.setupCookingTimer()
            return
        } else {
            // 如果不存在，创建新的烹饪页面
            android.util.Log.d("RecipeFragment", "创建新的炉头${burnerIndex + 1}烹饪Fragment")
            recipeCookingFragment = RecipeCookingFragment.newInstance(burnerViewModel, recipe, burnerIndex)
            transaction.add(R.id.recipe_operation_container, recipeCookingFragment!!, "recipe_cooking_$burnerIndex")
        }
        
        transaction.commit()
    }
    
    fun showRecipeOperation() {
        // 隐藏所有烹饪页面，显示菜谱操作页面
        val transaction = childFragmentManager.beginTransaction()
        
        // 隐藏所有炉头的烹饪页面
        for (i in 0..3) {
            val cookingFragment = childFragmentManager.findFragmentByTag("recipe_cooking_$i")
            cookingFragment?.let { transaction.hide(it) }
        }
        
        // 显示菜谱操作页面
        val operationFragment = childFragmentManager.findFragmentByTag("recipe_operation")
        operationFragment?.let { transaction.show(it) }
        
        transaction.commit()
        
        android.util.Log.d("RecipeFragment", "显示菜谱操作页面")
    }

    private fun updateAllBurnerFragments() {
        burnerFragments.forEach { fragment ->
            fragment.updateBurnerState()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 